package com.example.demo.controller;

import com.example.demo.common.AjaxResult;
import com.example.demo.common.AppVariable;
import com.example.demo.common.PasswordUtils;
import com.example.demo.common.UserSessionUtils;
import com.example.demo.entity.Userinfo;
import com.example.demo.entity.vo.UserinfoVO;
import com.example.demo.service.ArticleService;
import com.example.demo.service.UserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import static com.example.demo.common.AppVariable.USER_SESSION_KEY;

/**
 * @program: demo
 * @author: JCM
 * @create: 2023-07-31 18:05
 * @description:
 **/
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;
    @Autowired
    private ArticleService articleService;

    @RequestMapping("/reg")
    public AjaxResult reg(Userinfo userinfo) {
        // 1. 非空校验
        if(userinfo == null || !StringUtils.hasLength(userinfo.getUsername())
        || !StringUtils.hasLength(userinfo.getPassword())) {
            return AjaxResult.fail(-1,"非法参数");
        }
        // 密码加密
        userinfo.setPassword(PasswordUtils.encrypt(userinfo.getPassword()));
        return AjaxResult.success(userService.reg(userinfo));
    }

    @RequestMapping("/login")
    public AjaxResult login(HttpServletRequest request, String username, String password) {
        // 1. 非空校验
        if (!StringUtils.hasLength(username) || !StringUtils.hasLength(password)) {
            return AjaxResult.fail(-1,"用户不存在");
        }
        // 2. 查询数据库
        Userinfo userinfo =  userService.selectByUsername(username);
        if(userinfo != null && userinfo.getId() > 0) {
            // 用户名有效
            // 密码是否相等
            if (PasswordUtils.check(password,userinfo.getPassword())) {
                // 用户名和密码正确 登录成功

                // 将用户存储到 session 中
                HttpSession session = request.getSession(true);
                session.setAttribute(USER_SESSION_KEY,userinfo);
                userinfo.setPassword("");// 返回前端之前隐藏敏感（如密码）信息
                return AjaxResult.success(userinfo);
            }
        }
        return AjaxResult.success(0,null);
    }

    @RequestMapping("/showinfo")
    public AjaxResult showInfo(HttpServletRequest request) {
        UserinfoVO userinfoVO = new UserinfoVO();
        // 1.得到当前登录用户（从 session 中获取）
        Userinfo userinfo = UserSessionUtils.getUser(request);
        if (userinfo == null) {
            return AjaxResult.fail(-1,"非法参数");
        }
        // Spring 提供的深克隆方法
        BeanUtils.copyProperties(userinfo,userinfoVO);
        // 2. 得到用户发表的文章总数
        userinfoVO.setArtCount(articleService.getArtCountByUid(userinfo.getId()));
        return AjaxResult.success(userinfoVO);
    }

    @RequestMapping("/del")
    public AjaxResult delArt(HttpServletRequest request,Integer id) {
        if (id == null || id <= 0) {
            return AjaxResult.fail(-1,"非法参数");
        }
        Userinfo userinfo = UserSessionUtils.getUser(request);
        if(userinfo == null) {
            return AjaxResult.fail(-2,"用户未登录");
        }
        return AjaxResult.success(articleService.delArt(id,userinfo.getId()));
    }

    // 注销功能
    @RequestMapping("/logout")
    public AjaxResult logout(HttpSession session) {
        session.removeAttribute(USER_SESSION_KEY);
        return AjaxResult.success(1);
    }

    @RequestMapping("/getuserbyid")
    public AjaxResult getUserById(Integer id) {
        if(id == null || id <= 0) {
            return AjaxResult.fail(-1,"非法参数");
        }
        Userinfo userinfo = userService.getUserById(id);
        if(userinfo == null || userinfo.getId() <= 0) {
            return AjaxResult.fail(-1,"非法参数");
        }
        userinfo.setPassword("");
        // 查询当前用户发表的文章数
        UserinfoVO userinfoVO = new UserinfoVO();
        BeanUtils.copyProperties(userinfo,userinfoVO);
        userinfoVO.setArtCount(articleService.getArtCountByUid(id));
        return AjaxResult.success(userinfoVO);
    }
}

